<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 4/14/17
 * Time: 10:37 AM
 */

namespace api\modules\bank\behaviors;


use common\components\tools\Tools;
use common\models\Bank;
use common\models\BankGuaranteeCompanyBind;
use common\models\Custom;
use common\models\GuaranteeCompanyDotSite;
use yii\base\ActionFilter;
use yii\base\ErrorException;

class CheckAttribute extends ActionFilter
{
	public $request_data;
	public $bank;
	public $guarantee_company_dot_site;
	public $guarantee_company;
	public $bank_company_bind;
	public $cooperate;
	public $cmpseq;
	public $pics;
	public $custom;
	public $except_custom_must_find_actions;
	
	public function init()
	{
		parent::init(); // TODO: Change the autogenerated stub
		$data = Tools::arrayToObject($this->request_data);
		$this->bank = Bank::findOne(['sign_code'=>$data->bank_sign_code]);
		if (!$this->bank){
			throw new ErrorException('数据库中没有此合作银行', 1041);
		}
		$this->guarantee_company_dot_site = GuaranteeCompanyDotSite::findOne(['sign_code' => $data->guarantee_company_dot_site_sign_code]);
		if (!$this->guarantee_company_dot_site){
			throw new ErrorException('数据库中没有此担保公司网点', 1042);
		}
		if (!$this->guarantee_company_dot_site->guaranteeCompany){
			throw new ErrorException('数据库中没有此担保公司', 1043);
		}else{
			$this->guarantee_company = $this->guarantee_company_dot_site->guaranteeCompany;
		}
		$this->bank_company_bind = BankGuaranteeCompanyBind::findOne(['bank_id'=>$this->bank->id, 'guarantee_company_id'=>$this->guarantee_company->id]);
		if (!$this->bank_company_bind){
			throw new ErrorException('担保公司没有和银行完成绑定', 1044);
		}
		$this->cooperate = $this->bank_company_bind->getCooperate();
		$this->cmpseq = date("YmdHis") . rand(100000, 999999);
		if (isset($data->pics)){
			$pics = unserialize($data->pics);
			$_pics = [];
			foreach($pics as $k => $v){
				$_pics[$k]['picid'] = $v['image_type'];
				$_pics[$k]['picurl']  = $v['image_url'];
			}
			$this->pics = $_pics;
		}
		if (isset($data->guarantee_company_user_id)){
			$this->custom = Custom::findOne(['guarantee_company_id'=>$this->guarantee_company->id, 'guarantee_company_user_id'=>$data->guarantee_company_user_id]);
			if (!in_array(\Yii::$app->controller->action->id, $this->except_custom_must_find_actions)&&!$this->custom){
				throw new ErrorException('数据库中没有此客户', 1045);
			}
		}
	}
}